package jjn.round1;

import commons.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author Jjn
 * @since 2022-08-12 14:08
 */
public class LeetCode102_LevelOrderTraversalOfBinaryTree {
    
    
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if(root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()) {
            List<Integer> data = new ArrayList<>();
            List<TreeNode> tree = new ArrayList<>();
            while(queue.peek() != null) {
                TreeNode node = queue.poll();
                data.add(node.val);
                if(node.left != null) {
                    tree.add(node.left);
                }
                if(node.right != null) {
                    tree.add(node.right);
                }
            }
            for(TreeNode node : tree) {
                queue.offer(node);
            }
            list.add(data);
        }
        return list;
    }
    
}
